package com.example.demo.service;

import com.example.demo.Util.ProblemNotFoundException;
import com.example.demo.Util.Task;
import com.example.demo.mapper.ProblemMapper;
import com.example.demo.model.Answer;
import com.example.demo.model.CompileRequest;
import com.example.demo.model.Problem;
import com.example.demo.model.Question;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2022-09-20
 * Time:9:24
 */
@Service
public class CompileService {
    @Autowired
    private ProblemMapper problemMapper;

    public  HashMap<String,Object> compileAndRun(CompileRequest compileRequest){
//        System.out.println("用户的当前工作路径" + System.getProperty("user.dir"));
        HashMap<String,Object> map = new HashMap<>();
        try {
//        根据 id 重数据库中找到题目的详情==》等到测试用例代码
            Problem problem = problemMapper.selectOne(compileRequest.id);
            if (problem == null){
                // 抛出异常
                throw new ProblemNotFoundException();
            }
//        把用户的代码和测试用例代码，给拼接成一个完整的代码
//        测试用例代码
            String testCode = problem.getTestCode();
//        用户提交的代码
            String requestCode = compileRequest.code;

            String finalCode = mergeCode(requestCode,testCode);
//            System.out.println(finalCode);
//            System.out.println(requestCode);
//        创建一个 Task 实例，调用里面的 compileAndRun 来进行编译
            Task task = new Task();
            Question question = new Question();
            question.setCode(finalCode);
            Answer answer = task.compileAndRun(question);
//        根据 Task 运行的结果，包装成一个Http响应
            map.put("error",answer.getError());
            map.put("reason",answer.getReason());
            map.put("stdout",answer.getStdout());
            return map;
        }catch (ProblemNotFoundException e){
            e.printStackTrace();
        }
        map.put("error",3);
        map.put("reason","没有找到指定的题");
        map.put("stdout","");
        return map;
    }

    // 合并代码
    private String mergeCode(String requestCode, String testCode) {
       int index =  requestCode.lastIndexOf("}");
       String finalCode = requestCode.substring(0,index) + testCode + "}";
       return finalCode;
    }

}
